package com.itlong.cloud.intercept;

import com.itlong.cloud.POJO.PO.OperationLogPO;
import com.itlong.cloud.annotation.LoggerInfo;
import com.itlong.cloud.enumerate.SystemTypeEnum;
import com.itlong.cloud.equip.property.ICloudIntercomServiceClient;
import com.itlong.cloud.noncore.commons.IOperationLogServiceClient;
import com.itlong.cloud.utils.network.http.HttpProtocolUtil;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * <desc>
 *      操作日志拦截器
 * </desc>
 *
 * @createDate 2017-12-20.
 */
@Aspect
@Component
public class LogIntercept {
    // 定义一个切入点
    @Pointcut("execution(* com.itlong.cloud.controller.*.*(..)) && !@annotation(com.itlong.cloud.annotation.UnLogIntercept)")
    public void excudeService(){}

    @Autowired
    IOperationLogServiceClient iOperationLogServiceClient;
    @Autowired
    ICloudIntercomServiceClient iCloudIntercomServiceClient;

    /**
     * <desc>
     *      用户操作日志证拦截器
     *      注：每个系统的操作日志拦截器需在拦截器中指定SystemType 对应枚举类 SystemTypeEnum
     * <desc/>
     *
     * @param
     * @return
     * @author Chunjian.G
     * @createDate 2017-12-20
     */
    @After("excudeService() && @annotation(loggerInfo)")
    public void twiceAsOld(JoinPoint thisJoinPoint, LoggerInfo loggerInfo) throws Exception {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String uri = request.getRequestURI();
        MethodSignature signature = (MethodSignature) thisJoinPoint.getSignature();
        Method method=signature.getMethod();
        OperationLogPO log=new OperationLogPO();
        String sn = request.getParameter("sn");
        if (StringUtils.isNotBlank(sn)){
            log.setAccount(sn);
            log.setRealName(StringHandlerUtil.getDeviceIdBySn(sn));
            log.setIp(HttpProtocolUtil.getIpAddr(request));
            log.setSystemType(SystemTypeEnum.CLOUD_TALK_SERVER.getType());
            log.setOperationUse(loggerInfo.operateDesc());
            log.setUrl(uri);
            //保存操作记录
            iOperationLogServiceClient.save(log);
        }
    }
}
